package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {


    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkSpaceService workSpaceService;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        log.info("{}到{}营业额数据统计：", begin, end);
        TurnoverReportVO vo = new TurnoverReportVO();
        List<LocalDate> dateList = new ArrayList<>();
        while (begin.isBefore(end) || begin.isEqual(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        List<Double> turnoverList = new ArrayList<>();
        // 查询dateList中每日营业额数据
        for (LocalDate date : dateList) {
            // 因为date是LocalDate类型，不能直接作为SQL语句的参数，需要转换为LocalDateTime类型
            LocalDateTime beginTime = date.atStartOfDay();
            LocalDateTime endTime = beginTime.plusDays(1);
            Double sumAmount = orderMapper.getSumAmount(beginTime, endTime, Orders.COMPLETED);
            sumAmount = sumAmount == null ? 0.0 : sumAmount;
            turnoverList.add(sumAmount);
        }
        vo.setDateList(StringUtils.join(dateList,","));
        vo.setTurnoverList(StringUtils.join(turnoverList,","));
        return vo;
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

//        //日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
//        private String dateList;
//        //用户总量，以逗号分隔，例如：200,210,220
//        private String totalUserList;
//        //新增用户，以逗号分隔，例如：20,21,10
//        private String newUserList;
        UserReportVO vo = new UserReportVO();
        List<LocalDate> dateList = new ArrayList<>();
        while (begin.isBefore(end) || begin.isEqual(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        List<Integer> totalUserList = new ArrayList<>();   //总用户数量
        List<Integer> newUserList = new ArrayList<>();      //新增用户数量
        for (LocalDate date : dateList) {
            // 因为date是LocalDate类型，不能直接作为SQL语句的参数，需要转换为LocalDateTime类型
            LocalDateTime beginTime = date.atStartOfDay();
            LocalDateTime endTime = beginTime.plusDays(1);
            // 查询截止到某天的用户总量
            totalUserList.add(userMapper.getSumUserCount(endTime));
            // 获取某天新用户的数量---->createTime
            newUserList.add(userMapper.getNewUserCount(beginTime, endTime));

        }
        vo.setDateList(StringUtils.join(dateList,","));
        vo.setTotalUserList(StringUtils.join(totalUserList,","));
        vo.setNewUserList(StringUtils.join(newUserList,","));
        return vo;
    }

    /**
     * 订单统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        log.info("{}到{}的订单统计：", begin, end);
        List<LocalDate> dateList = new ArrayList<>();
        while (begin.isBefore(end) || begin.isEqual(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        List<Integer> orderCountList = new ArrayList<>(); //每日订单数
        List<Integer> validOrderCountList = new ArrayList<>(); //每日有效订单数
        for (LocalDate date : dateList) {
            // 因为date是LocalDate类型，不能直接作为SQL语句的参数，需要转换为LocalDateTime类型
            LocalDateTime beginTime = date.atStartOfDay();
            LocalDateTime endTime = beginTime.plusDays(1);
            Map<String,Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            Integer orderCount= orderMapper.countOrders(map);
            if(orderCount == null){
                orderCount = 0;
            }
            orderCountList.add(orderCount);  //每日订单数
            map.put("status", Orders.COMPLETED);
            orderCount= orderMapper.countOrders(map);
            if(orderCount == null){
                orderCount = 0;
            }
            validOrderCountList.add(orderCount); //每日有效订单数
        }
        Map<String,Object> map = new HashMap<>();
        map.put("end",begin);
        //订单总数
        Integer totalOrderCount=orderMapper.countOrders(map);
        //有效订单数
        map.put("status", Orders.COMPLETED);
        Integer validOrderCount=orderMapper.countOrders(map);
        //订单完成率
        Double orderCompletionRate=(double)validOrderCount/totalOrderCount;
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     *  指定时间内销量排行
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        log.info("{}到{}的销量排名：", begin, end);
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
//        List<String> nameList = new ArrayList<>();
//        List<Integer> numberList = new ArrayList<>();
        List<GoodsSalesDTO> salesTop10 = orderDetailMapper.getBestSeller(beginTime, endTime);
//        for (GoodsSalesDTO goodsSalesDTO : salesTop10) {
//            nameList.add(goodsSalesDTO.getName());
//            numberList.add(goodsSalesDTO.getNumber());
//        }
        List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 导出营业数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1、查询数据库，获取营业数据 --- 最近30天的数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        BusinessDataVO businessDataVO = workSpaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2、通过POI将数据写入Excel中  反射读取文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
         //基于模板创建一新的Excel表格对象
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //----获取表格的sheet标签页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据---时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);
            //---获取第四行
            XSSFRow row = sheet.getRow(3);
            //填充数据--营业额
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            //填充数据-订单完成率
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //填充数据--新增用户数
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //-----获取第五行
            row = sheet.getRow(4);
            //填充数据--有效订单数
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //填充数据--平均客单价
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            //-----填充明细数据  每天的营业数据  从第8行开始
            for (int i = 0; i < 30; i++) {
                //dateBegin = dateBegin.plusDays(1);
                LocalDate date = dateBegin.plusDays(i);
                // 获取营业数据
                BusinessDataVO businessData = workSpaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                // 获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3、通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            // 关闭资源
            out.close();
            excel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
